package edu.ccut.saturn.basecomponent.database.valuetype;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ValueTypeSetUtils {
	private static Map<String,IValueType> typeMap = new HashMap<String, IValueType>();
	
	private static final String VALUE_TYPE_PATH = "valuetype.properties";
	
	static {
		initalSets();
	}

	private static void initalSets() {
		
		InputStream is = ValueTypeSetUtils.class.getResourceAsStream(VALUE_TYPE_PATH);
		
		Properties properties = new Properties();
		
		try {
			properties.load(is);
			
			Enumeration<Object> keys = properties.keys();
			
			while (keys.hasMoreElements()){
				
				String key = (String)keys.nextElement();
				
				String value = properties.getProperty(key);
				
				typeMap.put(key, (IValueType)Class.forName(value).newInstance());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static Object getValueType(String type,String value){
		IValueType valueType = typeMap.get(type);
		
		if (valueType != null){
			return valueType.getSimpleType(value);
		}
		
		return typeMap.get("java.lang.String").getSimpleType(value);
	}
}
